/**
 * TODO
 *
 * @ClassName: AuthorizeController
 * @author: changhong
 * @since: 2020/5/15 14:58
 */
package life.changhongdeshijie.community.demo.controller;

import life.changhongdeshijie.community.demo.dto.AccessTokendto;
import life.changhongdeshijie.community.demo.dto.GitUser;
import life.changhongdeshijie.community.demo.mapper.UserMapper;
import life.changhongdeshijie.community.demo.model.User;
import life.changhongdeshijie.community.demo.provider.GitProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller()
public class AuthorizeController {
    @Autowired
    private GitProvider gitProvider;
    @Value("${Git.Client_id}")
    private String Client_id;
    @Value("${Git.Redirect_uri}")
    private String Redirect_id;
    @Value("${Git.Client_secret}")
    private String Client_secret;
    @Autowired
    private UserMapper userMapper;
    @GetMapping("/callback")
    public String callback(@RequestParam(name="code")String code,HttpServletResponse response){
        AccessTokendto accessTokendto = new AccessTokendto();
//        accessTokendto.setGrant_type("authorization_code");
        accessTokendto.setCode(code);
//        accessTokendto.setStatus(status);
        accessTokendto.setClient_id(Client_id);
        accessTokendto.setRedirect_uri(Redirect_id);
        accessTokendto.setClient_secret(Client_secret);
        String accessToken = gitProvider.getAccessToken(accessTokendto);
        GitUser gitUser = gitProvider.getUser(accessToken);
//        System.out.println(user.getName());
        if (gitUser!=null){
            User user = new User();
            String token = UUID.randomUUID().toString();
            user.setToken(token);
            user.setName(gitUser.getName());
            user.setAccountId(String.valueOf(gitUser.getId()));
            user.setGmtCreate(System.currentTimeMillis());
            user.setGmtModified(user.getGmtCreate());
            userMapper.insert(user);
            response.addCookie(new Cookie("token",token));
            //登陆成功，写cookie和session
            request.getSession().setAttribute("user",gitUser);
            return "redirect:/";
        }
        return "redirect:/";
    }
}
